<template>
  <a-modal
    :maskClosable="false"
    :title="title"
    centered
    :width="600"
    v-model="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
  >
    <a-form :form="form">
      <a-form-item
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        label="部门名称"
      >
        <a-input placeholder="请输入部门名称" v-decorator="['deptName', {rules: [{ required: true, message: '请输入部门名称' }]}]" />
        <a-input v-decorator="['deptId']" hidden></a-input>
        <a-input v-decorator="['parentId']" hidden></a-input>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script>
import { deptCreate, deptEdit } from '@/api/system/system'
import pick from 'lodash.pick'
export default {
  components: {
  },
  data () {
    return {
      visible: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      form: this.$form.createForm(this),
      title: '',
      type: ''
    }
  },
  beforeCreate () {
  },
  created () {
  },
  methods: {
    add (obj) {
      this.title = obj.title
      this.type = obj.type
      this.visible = true
      this.$nextTick(() => {
        this.form.resetFields()
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(obj.data, 'parentId'))
        })
      })
    },
    edit (obj) {
      this.title = obj.title
      this.type = obj.type
      this.visible = true
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(obj.data, 'deptId', 'deptName', 'parentId'))
      })
    },

    handleSubmit (e) {
      var _this = this
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          var data = JSON.parse(JSON.stringify(values))
          if (_this.type === 'add') {
            return deptCreate(data).then(res => {
              _this.$message.success('新增成功', 1)
              _this.visible = false
              _this.$emit('ok')
            }).finally(() => {
              _this.confirmLoading = false
            })
          } else {
            return deptEdit(data).then(res => {
              _this.$message.success('编辑成功', 1)
              _this.visible = false
              _this.$emit('ok')
            }).finally(() => {
              _this.confirmLoading = false
            })
          }
        }
      })
    }
  }
}
</script>
<style scoped>
  .tree{
    max-height: 400px;
    overflow: auto;
  }
</style>
